package com.cloudkinto.controller.stock;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.bo.stock.BoxStockByTypeQueryBo;
import com.cloudkinto.bo.stock.BoxStockLockingQueryBo;
import com.cloudkinto.bo.stock.ProductStockBySkuQueryBo;
import com.cloudkinto.bo.stock.ProductStockLockingQueryBo;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dto.stock.query.*;
import com.cloudkinto.entity.ReplenishmentPlanDo;
import com.cloudkinto.entity.ReplenishmentPlanOrderDo;
import com.cloudkinto.service.platform.vo.product.StockToPlatformReq;
import com.cloudkinto.service.stock.ProductStockService;
import com.cloudkinto.service.stock.vo.snap.ProductWeightReq;
import com.cloudkinto.vo.stock.ReplenishmentPlanVo;
import com.cloudkinto.vo.stock.StockLockingVo;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hua
 * @since 2024-10-28
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "oms库存模块")
@RequestMapping("/api/admin/oms/ProductStock")
public class ProductStockOmsController extends BaseController {
    public static Long userId;
    private final ProductStockService productStockService;

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return productStockService.pageInit(getCurrentUserId(), getTenantId(), getCompanyId(), "oms");
    }


    @UserSessionRequired
    @PostMapping("/addWeight")
    @ApiOperation(value = "库存管理设置权重", notes = "库存管理设置权重")
    public SingleResult addWeight(@RequestBody @Validated ProductWeightReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("修改成功", productStockService.addWeight(req, userId, companyId));
    }


    @UserSessionRequired
    @GetMapping("/productBySku")
    @ApiOperation(value = "产品的库存状态", notes = "产品的库存状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryIdList", value = "产品分类 多个逗号隔开"),
            @ApiImplicitParam(name = "skuAccurate", value = "sku精准搜索"),
            @ApiImplicitParam(name = "sku", value = "sku模糊搜索"),
            @ApiImplicitParam(name = "spuAccurate", value = "spu精准搜索"),
            @ApiImplicitParam(name = "spu", value = "spu模糊搜索"),
            @ApiImplicitParam(name = "stockStatus", value = "库存状态"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),
            @ApiImplicitParam(name = "sort", value = "排序方式"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = SkuStockDto.class))
    public PageResult productBySku(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String categoryIdList = request.getParameter("categoryIdList");
        if (StringUtils.isNotBlank(categoryIdList)) {
            map.put("categoryIdList", Arrays.asList(categoryIdList.split(",")));
        }
        String skuAccurate = request.getParameter("skuAccurate");
        String sku = request.getParameter("sku");
        String productName = request.getParameter("productName");
        String sort = request.getParameter("sort");
        String sortColumn = request.getParameter("sortColumn");
        map.put("skuAccurate", skuAccurate);
        map.put("sku", sku);
        map.put("spuAccurate", request.getParameter("spuAccurate"));
        map.put("spu", request.getParameter("spu"));
        map.put("productName", productName);
        map.put("sort", sort);
        map.put("sortColumn", sortColumn);
        map.put("source", "oms");
        map.put("tenantId", getTenantId());
        map.put("userId", getCurrentUserId());
        map.put("companyId", getCompanyId());
        map.put("current",request.getParameter("current"));
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("stockStatus", request.getParameter("stockStatus"));
        userId = getCurrentUserId();
        return productStockService.productBySku(map);
    }


    @UserSessionRequired
    @GetMapping("exportProduct")
    @ApiOperation(value = "导出所有数据excel")
    public void
    exportProduct(HttpServletRequest request,HttpServletResponse response) {
        Map<String, Object> map = this.getProductMap(request);
        userId = getCurrentUserId();

        productStockService.exportProduct(map,response);
    }

    private Map<String, Object> getProductMap(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        String categoryIdList = request.getParameter("categoryIdList");
        if (StringUtils.isNotBlank(categoryIdList)) {
            map.put("categoryIdList", Arrays.asList(categoryIdList.split(",")));
        }
        String skuAccurate = request.getParameter("skuAccurate");
        String sku = request.getParameter("sku");
        String productName = request.getParameter("productName");
        String sort = request.getParameter("sort");
        String sortColumn = request.getParameter("sortColumn");
        map.put("skuAccurate", skuAccurate);
        map.put("sku", sku);
        map.put("spuAccurate", request.getParameter("spuAccurate"));
        map.put("spu", request.getParameter("spu"));
        map.put("productName", productName);
        map.put("sort", sort);
        map.put("sortColumn", sortColumn);
        map.put("source", "oms");
        map.put("tenantId", getTenantId());
        map.put("userId", getCurrentUserId());
        map.put("companyId", getCompanyId());
        map.put("current",request.getParameter("current"));
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("stockStatus", request.getParameter("stockStatus"));
        String productIds = request.getParameter("productId");
        if (productIds != null) {
            map.put("productIds", Arrays.asList(productIds.split(",")));
        }else{
            map.put("productIds",null);
        }
        return map;
    }

    @UserSessionRequired
    @GetMapping("exportReplenishmentPlan")
    @ApiOperation(value = "导出所有补货计划数据excel")
    public void exportReplenishmentPlan(HttpServletRequest request,HttpServletResponse response) {
        Map<String, Object> map = this.getReplenishmentPlanMap(request);
        userId = getCurrentUserId();

        productStockService.exportReplenishmentPlan(map,response);
    }

    private Map<String, Object> getReplenishmentPlanMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String status = request.getParameter("status");
        map.put("status",status);
      String replenishmentPlans =  request.getParameter("replenishmentPlans");
      map.put("replenishmentPlans",replenishmentPlans);
        return map;

    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuAccurate", value = "sku精准搜索"),
            @ApiImplicitParam(name = "sku", value = "sku模糊搜索"),
            @ApiImplicitParam(name = "spuAccurate", value = "spu精准搜索"),
            @ApiImplicitParam(name = "spu", value = "spu模糊搜索"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @UserSessionRequired
    @GetMapping("/supplementPlanListPage")
    @ApiOperation(value = "补充计划分页查询", notes = "补充计划分页查询")
    public PageResult supplementPlanListPage(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String skuAccurate = request.getParameter("skuAccurate");
        String sku = request.getParameter("sku");
        map.put("skuAccurate", skuAccurate);
        map.put("sku", sku);
        map.put("spuAccurate", request.getParameter("spuAccurate"));
        map.put("spu", request.getParameter("spu"));
        map.put("batchNumber",request.getParameter("batchNumber"));
        map.put("status", request.getParameter("status"));
        map.put("current",request.getParameter("current"));
        map.put("pageSize",request.getParameter("pageSize"));
        map.put("userId",getCurrentUserId());
        userId=getCurrentUserId();

        return productStockService.supplementPlanListPage(map);

    }




    @UserSessionRequired
    @PostMapping("/productByIds")
    @ApiOperation(value = "生成补充计划", notes = "生成补充计划")
    public SingleResult productById(@RequestBody List<ReplenishmentPlanDo> lists) {
        Map<String, Object> map = new HashMap<>();
        map.put("source", "oms");
        map.put("tenantId", getTenantId());
        map.put("userId", userId);
        map.put("companyId", getCompanyId());
        map.put("lists", lists);
        return SingleResult.success("生成成功", productStockService.productByIds(map));
    }

    @UserSessionRequired
    @PutMapping("/generateDocument")
    @ApiOperation(value = "合并补货计划", notes = "合并补货计划")
    public SingleResult generateDocument(@RequestBody List<Long> ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("source", "oms");
        map.put("tenantId", getTenantId());
        map.put("ids", ids);
        map.put("userId", userId);
        productStockService.generateDocument(map);
        return SingleResult.success("生成成功");
    }


    @UserSessionRequired
    @PostMapping("/updateReplenishmentPlan")
    @ApiOperation(value = "补充计划修改", notes = "补充计划修改")
    public SingleResult updateSupplementPlan(@RequestBody ReplenishmentPlanVo replenishmentPlanVo) {
        List<ReplenishmentPlanDo> replenishmentPlanDoList = replenishmentPlanVo.getReplenishmentPlanDoList();
        productStockService.updateReplenishmentPlan(replenishmentPlanDoList);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/updateStatusSupplementPlan")
    @ApiOperation(value = "补充计划状态修改", notes = "补充计划单状态修改")
    public SingleResult deleteSupplementPlan(@RequestBody List<Long> ids ) {
        productStockService.updateOrderStatus(ids);
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/listPageBySku")
    @ApiOperation(value = "按产品查询", notes = "按产品查询")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = SkuStockPageDto.class))
    public PageResult listPageBySku(@RequestBody @Validated ProductStockBySkuQueryBo req) {
        req.setCompanyIdList(Collections.singletonList(getCompanyId()));
        req.setSource("oms");
        req.setTenantId(getTenantId());
        req.setUserId(getCurrentUserId());
        return productStockService.productListPageBySku(req);
    }

    @UserSessionRequired
    @PostMapping("getProductLockingStockDetail")
    @ApiOperation(value = "产品锁定库存查询", notes = "产品锁定库存查询")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockLockingVo.class))
    public PageResult getProductLockingStockDetail(@RequestBody @Validated ProductStockLockingQueryBo req) {
        req.setCompanyId(getCompanyId());
        return productStockService.getProductLockingStockDetail(req);
    }

    @UserSessionRequired
    @PostMapping("/omsExportBySku")
    @ApiOperation(value = "按产品查询导出", notes = "按产品查询导出")
    public void omsExportBySku(@RequestBody @Validated ProductStockBySkuQueryBo req, HttpServletResponse response) throws IOException {
        req.setCompanyIdList(Collections.singletonList(getCompanyId()));
        req.setSource("oms");
        req.setTenantId(getTenantId());
        req.setUserId(getCurrentUserId());
        productStockService.omsExportBySku(req, response);
    }

    @UserSessionRequired
    @PostMapping("/boxListPageByType")
    @ApiOperation(value = "按箱类型查询", notes = "按箱类型查询")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = BoxTypeStockPageDto.class))
    public PageResult boxListPageByType(@RequestBody @Validated BoxStockByTypeQueryBo req) {
        req.setCompanyIdList(Collections.singletonList(getCompanyId()));
        req.setSource("oms");
        req.setTenantId(getTenantId());
        req.setUserId(getCurrentUserId());
        return productStockService.boxListPageByType(req);
    }

    @UserSessionRequired
    @PostMapping("getBoxLockingStockDetail")
    @ApiOperation(value = "箱锁定库存查询", notes = "箱锁定库存查询")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = StockLockingVo.class))
    public PageResult getBoxLockingStockDetail(@RequestBody @Validated BoxStockLockingQueryBo req) {
        req.setCompanyId(getCompanyId());
        return productStockService.getBoxLockingStockDetail(req);
    }


    @UserSessionRequired
    @PostMapping("/omsExportByBoxTypeNo")
    @ApiOperation(value = "按箱类型查询导出", notes = "按箱类型查询导出")
    public void omsExportByBoxTypeNo(@RequestBody @Validated BoxStockByTypeQueryBo req, HttpServletResponse response) throws IOException {
        req.setCompanyIdList(Collections.singletonList(getCompanyId()));
        req.setSource("oms");
        req.setTenantId(getTenantId());
        req.setUserId(getCurrentUserId());
        productStockService.omsExportByBoxTypeNo(req, response);
    }


    @UserSessionRequired
    @GetMapping("/complexStockPage")
    @ApiOperation(value = "综合库存（分页）", notes = "综合库存（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storageIds", value = "仓库 多个,隔开"),
            @ApiImplicitParam(name = "skuAccurate", value = "sku精准搜索"),
            @ApiImplicitParam(name = "sku", value = "sku模糊搜索"),
            @ApiImplicitParam(name = "spuAccurate", value = "spu精准搜索"),
            @ApiImplicitParam(name = "spu", value = "spu模糊搜索"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),
            @ApiImplicitParam(name = "sort", value = "排序方式"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ComplexStockPageDto.class))
    public PageResult complexStockPage(HttpServletRequest request) {
        Map<String, Object> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return productStockService.complexStockPage(map);
    }


    @UserSessionRequired
    @GetMapping("/complexStock")
    @ApiOperation(value = "综合库存（总计）", notes = "综合库存（总计）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storageIds", value = "仓库 多个,隔开"),
            @ApiImplicitParam(name = "skuAccurate", value = "sku精准搜索"),
            @ApiImplicitParam(name = "sku", value = "sku模糊搜索"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),
            @ApiImplicitParam(name = "sort", value = "排序方式"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ComplexStockTotalDto.class))
    public SingleResult complexStock(HttpServletRequest request) {

        Map<String, Object> map = this.getMap(request);
        return SingleResult.success(productStockService.complexStock(map));
    }


    @UserSessionRequired
    @GetMapping("/complexStockExport")
    @ApiOperation(value = "综合库存导出", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id 多个,隔开"),
            @ApiImplicitParam(name = "storageIds", value = "仓库 多个,隔开"),
            @ApiImplicitParam(name = "skuAccurate", value = "sku精准搜索"),
            @ApiImplicitParam(name = "sku", value = "sku模糊搜索"),
            @ApiImplicitParam(name = "productName", value = "产品名称"),
            @ApiImplicitParam(name = "sort", value = "排序方式"),
            @ApiImplicitParam(name = "sortColumn", value = "排序列"),
    })
    public void boxExportFlowingOms(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = this.getMap(request);
        productStockService.complexStockExport(map, response);
    }


    public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String ids = request.getParameter("ids");
        if (ids != null) {
            map.put("ids", Arrays.asList(ids.split(",")));
        }
        String skuAccurate = request.getParameter("skuAccurate");
        String sku = request.getParameter("sku");
        String productName = request.getParameter("productName");
        String sort = request.getParameter("sort");
        String sortColumn = request.getParameter("sortColumn");
        String[] storageIds = request.getParameterValues("storageIds");
        map.put("skuAccurate", skuAccurate);
        map.put("sku", sku);
        map.put("productName", productName);
        map.put("sort", sort);
        map.put("sortColumn", sortColumn);
        if (storageIds != null && storageIds.length > 0) {
            map.put("storageIds", Arrays.asList(storageIds));
        }
        map.put("source", "oms");
        map.put("tenantId", getTenantId());
        map.put("userId", getCurrentUserId());
        map.put("companyId", getCompanyId());

        map.put("spuAccurate", request.getParameter("spuAccurate"));
        map.put("spu", request.getParameter("spu"));
        return map;
    }


    @UserSessionRequired
    @PostMapping("manalStockToPlat")
    @ApiOperation(value = "手動回传库存", notes = "手動回传库存")
    public SingleResult manalStockToPlat(@RequestBody @Validated StockToPlatformReq req) {
        productStockService.manalStockToPlat(req, getCurrentUserId(), getUserName());
        return SingleResult.success();
    }


}

